import {getMyAddressList, setAddressDefault} from '../../api/member.js';
import Util from '../../utils/util.js';

const app = getApp()
Page({
  data: {
    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    lists: [],
    et_show: true,

    default_id: null
  },

  onLoad: function (options) {
    // 当前页面参数
    const that = this;
    this.data.options = options;

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
        loadend: false,
        loading: false,
        list: [],
        page: 1,
      });

      that.getLists()
      wx.hideLoading()
    }).catch(errmsg => {
      wx.hideLoading()
    })
    this.onLoadTabbar();
  },

  onShow: function () {
    // 获取收货地址列表
    const that = this,
      is_refresh = wx.getStorageSync("is_refresh");

    if (is_refresh) {

      that.setData({
        loadend: false,
        loading: false,
        page: 1,
        lists: []
      });

      that.getLists()
      wx.removeStorageSync("is_refresh")
    }
  },

  getLists() {
    const that = this
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      wx.stopPullDownRefresh()
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});

    let filter = that.data.filter || {}
    filter['page_num'] = that.data.page;
    getMyAddressList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = app.SplitArray(list, lists);

      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        page: that.data.page + 1,
        et_show: lists.length > 0
      });

      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      wx.stopPullDownRefresh()
      app.Tips({title: errmsg})
    })
  },

  goToPage(e) {

    const that = this,
      from = this.data.options.from || '',
      id = e.currentTarget.dataset.aid;

    if (from === 'flow') {
      wx.setStorageSync("address_id", id);
      wx.navigateTo({
        url: "../cart/checkout?address_id=" + id
      })

      return;
    }

  },

  /**
   * 添加新地址
   */
  createAddress: function () {
    wx.navigateTo({
      url: './create'
    });
  },

  /**
   * 编辑地址
   */
  editAddress: function (e) {
    wx.navigateTo({
      url: "./detail?address_id=" + e.currentTarget.dataset.id
    });
  },

  /**
   * 移除收货地址
   */
  removeAddress: function (e) {
    let _this = this,
      address_id = e.currentTarget.dataset.id;

    wx.showModal({
      title: "提示",
      content: "您确定要移除当前收货地址吗?",
      success: function (o) {
        o.confirm && App._post_form('address/delete', {
          address_id
        }, function (result) {
          _this.getAddressList();
        });
      }
    });
  },

  /**
   * 设置为默认地址
   */
  setDefault: function (e) {
    const that = this;
    let key = e.currentTarget.dataset.k,
      lists = this.data.lists || [],
      address_id = e.detail.value;

    lists.forEach(e1 => {
      e1.is_default = 0;
    })
    lists[key].is_default = 1;

    wx.showLoading({title: "正在更新.."})
    setAddressDefault(lists[key].id).then(res => {
      that.setData({
        lists: lists
      })

      if (that.data.options.from === 'flow') {
        wx.setStorageSync("address_id", lists[key].id);
        wx.navigateTo({
          url: "../cart/checkout?address_id=" + lists[key].id
        })
      }

    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      wx.hideLoading()
    })
    return false;
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getLists();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: []
    });

    this.getLists();
    wx.stopPullDownRefresh()
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          let bottom = parseInt(rect.height) + 15;
          if (that.data.isIphoneX) {
            bottom += 20;
          }

          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },

});